package com.huqing.icu.service.impl;

import com.huqing.icu.dao.ChatFileDao;
import com.huqing.icu.enums.FileStatusEnum;
import com.huqing.icu.model.ChatFile;
import com.huqing.icu.service.IChatFileService;
import com.huqing.icu.service.vectorstore.IVectorStoreService;
import org.springframework.ai.document.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @Description 对话中的文件上传
 * @Author huqing
 * @Date 2025/8/25 18:09
 **/
@Service
public class ChatFileServiceImpl implements IChatFileService {

    @Autowired
    private ChatFileDao chatFileDao;
    @Autowired
    private IVectorStoreService iVectorStoreService;


    /**
     * 上传文件
     *
     * @param multipartFile
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer upload(MultipartFile multipartFile, Long userId) {
        String fileName = multipartFile.getName();
        String[] split = fileName.split(".");
        Integer lastIndex = split.length - 1;
        String fileType = split[lastIndex].toLowerCase();

        ChatFile chatFile = new ChatFile();
        chatFile.setUserId(userId);
        chatFile.setFileName(fileName);
        chatFile.setFileType(fileType);
        chatFile.setFileSize(multipartFile.getSize());
        chatFile.setStatus(FileStatusEnum.PENDING.getCode());
        chatFileDao.insert(chatFile);

        //解析文件并存到向量库
        List<Document> documentList = iVectorStoreService.read(multipartFile.getResource(), fileName);
        iVectorStoreService.saveVectorStore(documentList, fileName);
        return 1;
    }
}
